取得權限的前置作業
iOS
Info.plist內新增
NSPhotoLibraryUsageDescription的權限
Android
AndroidManifest.xml 內新增<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
在getImage()裡面 呼叫GallerySaver.saveImage(), 並給圖片路徑.
getImage(ImageSource source) async {
final _picker = ImagePicker();
XFile? pickedFile = await _picker.pickImage(source: source);
if (pickedFile != null) {
imageFilePath = await cropImage(pickedFile.path);
GallerySaver.saveImage(imageFilePath);
}
}
如果圖片來源自網址
saveFromUrl(String urlPath) async {
GallerySaver.saveImage(urlPath).then((bool success) {
//success callback
});
}
來源自網址的影片也可以下載到手機相簿裡
之前處理這段遇到了一個問題是
GallerySaver雖然可以自動判斷是本地路徑或是url
但如果來源的網址很長或被判斷是不可下載的網址
作法改成:
Future<bool> saveVideoToAlbum(String urlPath) async {
//先創一個暫時路徑, getTemporaryDirectory() 需導入path_provider
Directory appDocDir = await getTemporaryDirectory();
final String timeStamp = DateTime.now().millisecondsSinceEpoch.toString();
//檔名暫時用timeStamp命名
String temporaryPath = appDocDir.path + "$timeStamp.mp4";
//把檔案用Dio download存到暫時路徑
final response = await Dio().download(urlPath, temporaryPath,
onReceiveProgress: (count, total) {
//這邊是下載進度的換算, 可以從這裡取出數值
print((count / total * 100).toStringAsFixed(0) + "%");
});
//再用GallerySaver存到相簿
bool? isSucceed = await GallerySaver.saveVideo(temporaryPath);
if (isSucceed != null) {
if (isSucceed) {
//最後再將暫存的檔案刪除
deleteTemporaryFile(temporaryPath);
return true;
}
}
return false;
}
deleteTemporaryFile(String filePath) async {
try {
await File(filePath).delete();
} catch (error) {
print('Delete TemporaryFile error');
print(error);
}
}
下一篇將為大家介紹 flutter_slidable
ListView(iOS的 tableView)左右滑動的操作